from flask import Blueprint, request, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from app import db
from app.models import Case, Patient, Doctor, Ward, Bed
from app.utils import custom_jsonify
import datetime

case_bp = Blueprint('case', __name__)

@case_bp.route('/add_patient', methods=['GET'])
@case_bp.route('/addCase', methods=['GET', 'POST'])
@login_required
def add_case():
    if request.method == 'GET':
        return render_template('add_patient.html')
        
    try:
        # 获取请求数据
        data = request.get_json() if request.is_json else request.form.to_dict()
        
        if not data:
            return custom_jsonify({"msg": "failed", "error": "无效的请求数据"}, 400)
        
        # 验证必要字段
        required_fields = ['patient_id', 'patient_name', 'dept_name', 'description']
        missing_fields = [field for field in required_fields if not data.get(field)]
        if missing_fields:
            return custom_jsonify({
                "msg": "failed", 
                "error": f"缺少必要字段: {', '.join(missing_fields)}"
            }, 400)
        
        # 验证病人存在
        patient = Patient.query.get(data['patient_id'])
        if not patient:
            return custom_jsonify({"msg": "failed", "error": "病人不存在"}, 404)
            
        # 使用当前登录医生信息
        doctor_id = current_user.doctor_id
        
        # 检查是否存在活跃病例
        existing_case = Case.query.filter_by(
            patient_id=data['patient_id'],
            description=data['description']
        ).first()
        
        if existing_case:
            return custom_jsonify({"msg": "failed", "error": "该病人已存在相同描述的病例"}, 409)
        
        # 生成病例ID
        today = datetime.datetime.now().strftime("%Y%m%d")
        case_count = Case.query.filter(
            Case.dept_name == data['dept_name'],
            Case.case_id.like(f"CS-{today}%")
        ).count()
        case_id = f"CS-{today}{case_count + 1:03d}"
        
        # 创建新病例
        new_case = Case(
            case_id=case_id,
            patient_id=data['patient_id'],
            doctor_id=doctor_id,
            dept_name=data['dept_name'],
            description=data['description'],
            predict_days=data.get('predict_days', 7)
        )
        
        db.session.add(new_case)
        db.session.commit()
        
        return custom_jsonify({
            "msg": "success",
            "case_info": {
                "case_id": case_id,
                "patient_name": patient.patient_name,
                "doctor_name": current_user.doctor_name,
                "dept_name": data['dept_name'],
                "description": data['description']
            }
        })
            
    except Exception as e:
        db.session.rollback()
        return custom_jsonify({"msg": "failed", "error": str(e)}, 500)

@case_bp.route('/api/patients/search')
@login_required
def search_patient():
    query = request.args.get('query', '')
    if not query:
        return custom_jsonify({
            "msg": "failed",
            "error": "请输入搜索内容"
        }, 400)
    
    try:
        # 尝试通过ID或姓名搜索病人
        patient = Patient.query.filter(
            (Patient.patient_id == query) | 
            (Patient.patient_name.like(f'%{query}%'))
        ).first()
        
        if patient:
            return custom_jsonify({
                "msg": "success",
                "patient": {
                    "patient_id": patient.patient_id,
                    "patient_name": patient.patient_name,
                    "gender": patient.gender,
                    "age": patient.age
                }
            })
        
        return custom_jsonify({
            "msg": "failed",
            "error": "未找到病人"
        }, 404)
        
    except Exception as e:
        return custom_jsonify({
            "msg": "failed",
            "error": str(e)
        }, 500)
